package com.insist.service.impl;

import com.insist.dao.*;
import com.insist.entity.*;
import com.insist.enums.CmmNoType;
import com.insist.framework.CmmBaseResponse;
import com.insist.model.OrderDetailInfoModel;
import com.insist.service.OrderService;
import com.insist.service.ProductService;
import com.insist.service.RewardService;
import com.insist.service.UserService;
import com.insist.util.BeanCopierUtils;
import com.insist.util.CmmUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/7/1.
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderInfoDao orderInfoDao;
    @Autowired
    OrderDetailInfoDao orderDetailInfoDao;

    @Autowired
    CartInfoDao cartInfoDao;

    @Autowired
    ProductService productService;
    @Autowired
    UserInfoDao userInfoDao;
    @Autowired
    RewardService rewardService;
    @Autowired
    UserService userService;
    @Autowired
    AccountFlowDao accountFlowDao;

    @Override
    public CmmBaseResponse createOrder(Long userId) {
        UserInfo userInfo = userInfoDao.getOne(userId);

        List<CartInfo> cartInfoList = cartInfoDao.findByUserId(userId);
        List<OrderDetailInfo> orderDetailInfos = new ArrayList<>();
        Double price = 0.0;
        final List<ProductInfo> productInfos  = new ArrayList<>();
        String errorMsg = "";
        for(CartInfo cartInfo:cartInfoList){
            ProductInfo productInfo = productService.getProductById(cartInfo.getProductId());
            OrderDetailInfo orderDetailInfo = new OrderDetailInfo();
            orderDetailInfo.setUserId(userId);
            orderDetailInfo.setNumber(cartInfo.getNum());
            orderDetailInfo.setPrice(productInfo.getPrice());
            orderDetailInfo.setProductId(productInfo.getId());
            orderDetailInfo.setCreateTime(new Date());
            orderDetailInfo.setProductNo(productInfo.getProductNo());
            orderDetailInfos.add(orderDetailInfo);
            price+=productInfo.getPrice()*cartInfo.getNum();
            if(productInfo.getBuyNum() + cartInfo.getNum()>productInfo.getTotalNum()){
                errorMsg+="商品"+productInfo.getName()+"只剩余"+(productInfo.getTotalNum()-productInfo.getBuyNum())+"份;\n";
            }

            productInfo.setBuyNum(productInfo.getBuyNum()+cartInfo.getNum());
            ProductInfo newInfo = new ProductInfo();
            BeanCopierUtils.copyProperties(productInfo, newInfo);
            productInfos.add(newInfo);
        }
        if(errorMsg.length()>0){
            return CmmBaseResponse.buildResponse(false,errorMsg);
        }
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setStatu(1);
        orderInfo.setTotalPrice(price);
        orderInfo.setOrderNo(CmmUtils.createOrderNo(CmmNoType.ORDER));
        orderInfo = orderInfoDao.save(orderInfo);
        for(OrderDetailInfo orderDetailInfo:orderDetailInfos){
            orderDetailInfo.setOrderId(orderInfo.getId());
        }
        orderDetailInfoDao.save(orderDetailInfos);

        if(userInfo.getAccount() < orderInfo.getTotalPrice()){
            return CmmBaseResponse.buildResponse(false,"创建订单失败,余额不足");
        }
        userInfo.setAccount(userInfo.getAccount() - orderInfo.getTotalPrice());
        userInfoDao.save(userInfo);
        orderInfo.setStatu(2);
        orderInfoDao.save(orderInfo);
        cartInfoDao.deleteInBatch(cartInfoList);
        new Thread(new Runnable() {
            @Override
            public void run() {
                rewardService.checkProducts(productInfos);
            }
        }).start();

        //消费流水
        AccountFlowInfo accountFlowInfo = new AccountFlowInfo();
        accountFlowInfo.setBizId(orderInfo.getId());
        accountFlowInfo.setUserId(userId);
        accountFlowInfo.setCreateTime(new Date());
        accountFlowInfo.setMessage("订单" + orderInfo.getOrderNo() + "消费");
        accountFlowInfo.setType(2);
        accountFlowInfo.setMoney(orderInfo.getTotalPrice());
        accountFlowDao.save(accountFlowInfo);

        //消费返利
        Integer fanli =Double.valueOf(orderInfo.getTotalPrice()/100).intValue();
        if(fanli>0){
            AccountFlowInfo accountFlowInfo2 = new AccountFlowInfo();
            accountFlowInfo2.setBizId(orderInfo.getId());
            accountFlowInfo2.setUserId(userId);
            accountFlowInfo2.setCreateTime(new Date());
            accountFlowInfo2.setMessage("订单" + orderInfo.getOrderNo() + "消费返利");
            accountFlowInfo2.setType(1);
            accountFlowInfo2.setMoney(fanli + 0.0);
            accountFlowDao.save(accountFlowInfo2);

            userInfo.setAccount(userInfo.getAccount() + fanli);
            userInfoDao.save(userInfo);
        }

        return CmmBaseResponse.buildResponse(true,"创建订单成功");
    }

    @Override
    public CmmBaseResponse createOrder(Long userId, Long productId,Integer number) {
        UserInfo userInfo = userInfoDao.getOne(userId);

//        CartInfo cartInfo = cartInfoDao.getByProductIdAndUserId(productId, userId);
        Double price = 0.0;

        final List<ProductInfo> productInfos  = new ArrayList<>();

        ProductInfo productInfo = productService.getProductById(productId);
        OrderDetailInfo orderDetailInfo = new OrderDetailInfo();
        orderDetailInfo.setUserId(userId);
        orderDetailInfo.setNumber(number);
        orderDetailInfo.setPrice(productInfo.getPrice());
        orderDetailInfo.setProductId(productInfo.getId());
        orderDetailInfo.setCreateTime(new Date());
        orderDetailInfo.setProductNo(productInfo.getProductNo());
        price+=productInfo.getPrice()*number;
        if(productInfo.getBuyNum() + number>productInfo.getTotalNum()){
            return CmmBaseResponse.buildResponse(false,"创建失败，商品数量只剩余"+(productInfo.getTotalNum()-productInfo.getBuyNum())+"份");
        }

        productInfo.setBuyNum(productInfo.getBuyNum() + number);
        ProductInfo newInfo = new ProductInfo();
        BeanCopierUtils.copyProperties(productInfo, newInfo);
        productInfos.add(newInfo);

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setStatu(1);
        orderInfo.setTotalPrice(price);
        orderInfo.setOrderNo(CmmUtils.createOrderNo(CmmNoType.ORDER));
        orderInfo = orderInfoDao.save(orderInfo);
        orderDetailInfo.setOrderId(orderInfo.getId());
        orderDetailInfoDao.save(orderDetailInfo);

        if(userInfo.getAccount() < orderInfo.getTotalPrice()){
            return CmmBaseResponse.buildResponse(false,"创建订单失败,余额不足");
        }
        userInfo.setAccount(userInfo.getAccount() - orderInfo.getTotalPrice());
        userInfoDao.save(userInfo);
        orderInfo.setStatu(2);
        orderInfoDao.save(orderInfo);
        new Thread(new Runnable() {
            @Override
            public void run() {
                rewardService.checkProducts(productInfos);
            }
        }).start();

        //消费流水
        AccountFlowInfo accountFlowInfo = new AccountFlowInfo();
        accountFlowInfo.setBizId(orderInfo.getId());
        accountFlowInfo.setUserId(userId);
        accountFlowInfo.setCreateTime(new Date());
        accountFlowInfo.setMessage("订单" + orderInfo.getOrderNo() + "消费");
        accountFlowInfo.setType(2);
        accountFlowInfo.setMoney(orderInfo.getTotalPrice());
        accountFlowDao.save(accountFlowInfo);

        //消费返利
        Integer fanli =Double.valueOf(orderInfo.getTotalPrice()/100).intValue();
        if(fanli>0){
            AccountFlowInfo accountFlowInfo2 = new AccountFlowInfo();
            accountFlowInfo2.setBizId(orderInfo.getId());
            accountFlowInfo2.setUserId(userId);
            accountFlowInfo2.setCreateTime(new Date());
            accountFlowInfo2.setMessage("订单" + orderInfo.getOrderNo() + "消费返利");
            accountFlowInfo2.setType(1);
            accountFlowInfo2.setMoney(fanli + 0.0);
            accountFlowDao.save(accountFlowInfo2);

            userInfo.setAccount(userInfo.getAccount() + fanli);
            userInfoDao.save(userInfo);
        }

        CmmBaseResponse response= CmmBaseResponse.buildResponse(true, "创建订单成功");
        response.setData(orderInfo);
        return response;
    }

    @Override
    public List<OrderDetailInfoModel> findAllOrderDetails(Long loginUserId) {
        List<OrderDetailInfoModel> rsList = new ArrayList<>();
        List<OrderDetailInfo> orderDetails = orderDetailInfoDao.findByUserId(loginUserId);
        for(OrderDetailInfo detailInfo:orderDetails){
            ProductInfo product = productService.getProductById(detailInfo.getProductId());
            OrderInfo order = orderInfoDao.getOne(detailInfo.getOrderId());
            OrderDetailInfoModel detailInfoModel = new OrderDetailInfoModel();
            BeanCopierUtils.copyProperties(detailInfo, detailInfoModel);
            detailInfoModel.setProductName(product.getName());
            detailInfoModel.setTotalNum(product.getTotalNum());
            detailInfoModel.setOrderNo(order.getOrderNo());
            rsList.add(detailInfoModel);
        }
        return rsList;
    }

    @Override
    public List<OrderDetailInfoModel> findAllOrderDetails(Long loginUserId,Long orderId) {
        List<OrderDetailInfoModel> rsList = new ArrayList<>();
        List<OrderDetailInfo> orderDetails = orderDetailInfoDao.findByUserIdAndOrderId(loginUserId,orderId);
        for(OrderDetailInfo detailInfo:orderDetails){
            ProductInfo product = productService.getProductById(detailInfo.getProductId());
            OrderInfo order = orderInfoDao.getOne(detailInfo.getOrderId());
            OrderDetailInfoModel detailInfoModel = new OrderDetailInfoModel();
            BeanCopierUtils.copyProperties(detailInfo, detailInfoModel);
            detailInfoModel.setProductName(product.getName());
            detailInfoModel.setTotalNum(product.getTotalNum());
            detailInfoModel.setOrderNo(order.getOrderNo());
            rsList.add(detailInfoModel);
        }
        return rsList;
    }

    @Override
    public List<OrderInfo> findAllOrders(Long loginUserId) {
        return orderInfoDao.findByUserId(loginUserId);
    }

    @Override
    public List<OrderDetailInfoModel> findActorByProductId(Long productId) {
        List<OrderDetailInfoModel> rsList = new ArrayList<>();
        List<OrderDetailInfo> orderDetails = orderDetailInfoDao.findByProductId(productId);
        for(OrderDetailInfo detailInfo:orderDetails){
            UserInfo userInfo = userService.getById(detailInfo.getUserId());
            OrderDetailInfoModel detailInfoModel = new OrderDetailInfoModel();
            detailInfoModel.setCreateTime(detailInfo.getCreateTime());
            detailInfoModel.setUsername(userInfo.getUsername());
            detailInfoModel.setUserImg(userInfo.getImage());
            rsList.add(detailInfoModel);
        }
        return rsList;
    }

    @Override
    public String getMaxOrderNo() {
        return orderInfoDao.getMaxOrderNo();
    }
}
